#!/usr/bin/ash
#
# SPDX-License-Identifier: GPL-3.0-or-later

run_hook() {
    local img_label

    img_label=$(getarg 'img_label')
    img_dev="$(getarg 'img_dev')"
    [ -n "${img_label}" ] && img_dev="$(getarg 'img_dev' "/dev/disk/by-label/${img_label}")"
    img_flags="$(getarg 'img_flags' 'defaults')"
    img_loop="$(getarg 'img_loop')"
    if [ -n "${img_dev}" ] && [ -n "${img_loop}" ]; then
        export mount_handler="lingmo_loop_mount_handler"
    fi
}

lingmo_loop_mount_handler() {
    newroot="${1}"

    local _dev_loop

    msg ":: Setup a loop device from ${img_loop} located at device ${img_dev}"
    _mnt_dev "${img_dev}" "/run/lingmo/img_dev" "-r" "${img_flags}"

    if _dev_loop=$(losetup --find --show --read-only "/run/lingmo/img_dev/${img_loop}"); then
        export lingmodevice="${_dev_loop}"
    else
        echo "ERROR: Setting loopback device for file '/run/lingmo/img_dev/${img_loop}'"
        launch_interactive_shell
    fi

    lingmo_mount_handler "${newroot}"

    # shellcheck disable=SC2154
    # defined via initcpio's parse_cmdline()
    if [ "${copytoram}" = "y" ]; then
        losetup -d "${_dev_loop}" 2>/dev/null
        umount /run/lingmo/img_dev
    fi
}

# vim: set ft=sh:
